import java.io.IOException;
import java.io.PrintStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.DecimalFormat;

public class SntpClient {
	public static void main(String[] args) throws IOException {
		String serverName;
		if (args.length == 1) {
			serverName = args[0];
		} else {
			printUsage();
			return;
		}
		// String serverName;
		DatagramSocket socket = new DatagramSocket();
		InetAddress address = InetAddress.getByName(serverName);
		byte[] buf = new NtpMessage().toByteArray();
		DatagramPacket packet = new DatagramPacket(buf, buf.length, address,
				123);

		NtpMessage.encodeTimestamp(packet.getData(), 40,
				System.currentTimeMillis() / 1000.0D + 2208988800.0D);

		socket.send(packet);

		System.out.println("NTP request sent, waiting for response...\n");
		packet = new DatagramPacket(buf, buf.length);
		socket.receive(packet);

		double destinationTimestamp = System.currentTimeMillis() / 1000.0D + 2208988800.0D;

		NtpMessage msg = new NtpMessage(packet.getData());

		double roundTripDelay = destinationTimestamp - msg.originateTimestamp
				- (msg.transmitTimestamp - msg.receiveTimestamp);

		double localClockOffset = (msg.receiveTimestamp
				- msg.originateTimestamp + (msg.transmitTimestamp - destinationTimestamp)) / 2.0D;

		System.out.println("NTP server: " + serverName);
		System.out.println(msg.toString());

		System.out.println("Dest. timestamp:     "
				+ NtpMessage.timestampToString(destinationTimestamp));

		System.out.println("Round-trip delay: "
				+ new DecimalFormat("0.00").format(roundTripDelay * 1000.0D)
				+ " ms");

		System.out.println("Local clock offset: "
				+ new DecimalFormat("0.00").format(localClockOffset * 1000.0D)
				+ " ms");

		socket.close();
	}

	static void printUsage() {
		System.out
				.println("NtpClient - an NTP client for Java.\n\nThis program connects to an NTP server and prints the response to the console.\n\n\nUsage: java NtpClient server\n\n\nThis program is copyright (c) Adam Buckley 2004 and distributed under the terms\nof the GNU General Public License.  This program is distributed in the hope\nthat it will be useful, but WITHOUT ANY WARRANTY; without even the implied\nwarranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nGeneral Public License available at http://www.gnu.org/licenses/gpl.html for\nmore details.");
	}
}